package com.sbtr.util;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

/**
 * 实体类属性copy具类
 */
public class BeanCopyUtils {
	private BeanCopyUtils() {}
	private static final Logger logger = LoggerFactory.getLogger(BeanCopyUtils.class);

	/**
	 * 单个实体类属性值copy
	 * @param source
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> T copyProperties(Object source, Class<T> clazz){
		T t = null;
		try {
			if(source != null){
				t = clazz.newInstance();
				BeanUtils.copyProperties(source, t);
			}
		} catch (Exception e) {
			logger.error("复制bean属性异常", e);
		}
		return t;
	}

	/**
	 * 同一实体类，集合进行copy
	 * @param sources
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> List<T> copyProperties(List<? extends Object> sources, Class<T> clazz){
		List<T> result = new ArrayList<>();
		
		try {
			if(!CollectionUtils.isEmpty(sources)){
				for(Object obj : sources){
					T t = clazz.newInstance();
					BeanUtils.copyProperties(obj, t);
					result.add(t);
				}
			}
		} catch (Exception e) {
			logger.error("复制bean属性异常", e);
		}
		return result;
	}

}
